import { createSlice } from "@reduxjs/toolkit";
import type { RootState } from "../index";
import echarts from "@/plugins/echarts.plugin";
import useTheme from "@/hooks/useTheme";

interface EchartsSliceState {
  pieOptions: any;
  lineOptions: any;
}

const initialState: EchartsSliceState = {
  pieOptions: {
    tooltip: {},
    legend: {
      bottom: 20,
      left: "center",
      itemWidth: 8,
      itemHeight: 8,
      borderRadius: 10,
      icon: "circle",
    },
    series: [
      {
        name: "",
        type: "pie",
        center: ["50%", "40%"],
        radius: ["55%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 4,
          borderColor: "#fff",
          borderWidth: 2,
        },
        labelLine: {
          show: false,
        },
        data: [],
      },
    ],
  },
  lineOptions: {
    xAxis: {
      type: "category",
      data: [],
      axisTick: {
        alignWithLabel: true,
      },
    },
    grid: {
      left: 60,
      right: 30,
      bottom: 50,
      top: 20,
    },
    tooltip: {
      trigger: "axis",
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        showSymbol: false,
        symbolSize: 14,
        data: [],
        type: "line",
        emphasis: {
          itemStyle: {
            borderWidth: 4,
            shadowColor: "rgba(0, 0, 0, 0.1)",
            shadowBlur: 10,
          },
        },
        smooth: true,
      },
    ],
  },
};

export const echartsSlice = createSlice({
  name: "echarts",
  initialState,
  reducers: {
    updateAreaStyle(state, action) {
      state.lineOptions.series[0].areaStyle = {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: `rgba(${action.payload},1)`,
          },
          {
            offset: 1,
            color: `rgba(${action.payload},0)`,
          },
        ]),
      };
    },
  },
});
export const { updateAreaStyle } = echartsSlice.actions;
export const pieOptions = (state: RootState) => state.echarts.pieOptions;
export const lineOptions = (state: RootState) => state.echarts.lineOptions;

export default echartsSlice.reducer;
